package com.qinglei.recoup.hmp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.hmp.domain.HmpUserBindDevice;
import com.qinglei.recoup.hmp.pojo.parm.DeviceVersionParam;
import com.qinglei.recoup.hmp.pojo.vo.*;
import com.qinglei.recoup.hmp.pojo.vo.healthReport.HealthReportDayVo;
import com.qinglei.recoup.hmp.pojo.vo.healthReport.HealthReportOneDayVo;
import com.qinglei.recoup.hmp.service.HmpDeviceService;
import com.qinglei.recoup.hmp.service.HmpHealthReportService;
import com.qinglei.recoup.hmp.service.HmpUserBindDeviceService;
import com.qinglei.recoup.system.domain.Radar;
import com.qinglei.recoup.system.domain.RadarBed;
import com.qinglei.recoup.system.domain.RealTimeMonitoring;
import com.qinglei.recoup.system.pojo.AlarmEventItemVO;
import com.qinglei.recoup.system.pojo.PageParam;
import com.qinglei.recoup.system.pojo.RealTimeDataVOV7;
import com.qinglei.recoup.system.service.RadarBedService;
import com.qinglei.recoup.system.service.RadarDataService;
import com.qinglei.recoup.system.service.RadarService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;

/**
 * <p>小程序设备相关接口</p>
 *
 * @author shiyupeng
 * @date 2022/1/8
 */
@Api(tags = "【小程序】设备相关接口")
@Slf4j
@Validated
@RestController
@RequestMapping("hmp/device")
public class HmpDeviceController {

    @Autowired
    private HmpDeviceService hmpDeviceService;

    @Autowired
    private HmpHealthReportService hmpHealthReportService;
    @Resource
    private HmpUserBindDeviceService hmpUserBindDeviceService;

    /**
     * 调式用用户ID
     */
//    private Long userId = 1L;

//    @ApiOperation(value = "【废弃】通过设备SN码校验设备接口")
//    @ApiIgnore
//    @Deprecated
//    @PostMapping("/checkBind")
//    public CommonRes<DeviceCheckBindVO> checkBind(@RequestBody DeviceSnParam param) {
//        log.info("checkBind param:{}", param);
//        // TODO
//        return CommonRes.ok();
//    }

//    @ApiOperation(value = "【废弃】检查监测状态接口")
//    @ApiImplicitParam(name = "sn", value = "设备SN码", paramType = "query", dataType = "string", required = true)
//    @ApiIgnore
//    @Deprecated
//    @GetMapping("/checkStatus")
//    public CommonRes<DeviceCheckStatusVO> checkStatus(@NotNull String sn) {
//        log.info("checkStatus sn:{}", sn);
//        // TODO
//        return CommonRes.ok();
//    }

//    @ApiOperation(value = "【废弃】获取设备使用者标签列表接口")
//    @ApiIgnore
//    @Deprecated
//    @GetMapping("/userTagList")
//    public CommonRes<List<UserTagVO>> userTagList() {
//        log.info("userTagList in");
//        // TODO
//        return CommonRes.ok();
//    }
    @ApiOperation(value = "检查当前用户是否已绑定设备")
    @GetMapping("/checkBind")
    public CommonRes<DeviceCheckBindVO> checkBind() {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("checkBind in userId:{}", userId);
        CommonRes<DeviceCheckBindVO> res = hmpDeviceService.checkBind(userId);
        log.info("checkBind return:{}", res);
        return res;
    }

    @ApiOperation(value = "设置设备使用者标签接口")
    @PostMapping("/bindUserTag")
    public CommonRes<Object> bindUserTag(@RequestBody @Valid BindUserTagParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("bindUserTag userId:{}, param:{}", userId, param);
        CommonRes<Object> res = hmpDeviceService.bindUserTag(userId, param);
        log.info("bindUserTag return:{}", res);
        return res;
    }

    @ApiOperation(value = "设置设备属性接口")
    @PostMapping("/setAttr")
    public CommonRes<Object> setDeviceAttr(@RequestBody @Valid DeviceAttrParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("setDeviceAttr userId:{}, param:{}", userId, param);
        CommonRes<Object> res = hmpDeviceService.setDeviceAttr(userId, param);
        log.info("setDeviceAttr return:{}", res);
        return res;
    }

    @ApiOperation(value = "设置默认设备接口")
    @PostMapping("/setDefault")
    public CommonRes<Object> setDefaultDevice(@RequestBody @Valid DeviceSnParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("setDefaultDevice userId:{}, param:{}", userId, param);
        CommonRes<Object> res = hmpDeviceService.setDefaultDevice(userId, param);
        log.info("setDefaultDevice return:{}", res);
        return res;
    }

    @ApiOperation(value = "取消绑定设备接口")
    @PostMapping("/cancelBind")
    public CommonRes<Object> cancelBindDevice(@RequestBody @Valid DeviceSnParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("cancelBindDevice userId:{}, param:{}", userId, param);
        CommonRes<Object> res = hmpDeviceService.cancelBindDevice(userId, param);
        log.info("cancelBindDevice return:{}", res);
        return res;
    }

    @ApiOperation(value = "查询更多设备接口")
    @GetMapping("/list")
    public CommonRes<IPage<DeviceVO>> getDevicePage(PageParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("getDevicePage userId:{}, param:{}", userId, param);
        CommonRes<IPage<DeviceVO>> res = hmpDeviceService.getDevicePage(userId, param);
        log.info("getDevicePage return:{}", res);
        return res;
    }

    @ApiOperation(value = "获取睡眠日历接口")
    @GetMapping("/detail")
    public CommonRes<DeviceDetailVO> getDeviceDetail(DeviceDetailParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("getDeviceDetail userId:{}, param:{}", userId, param);
        CommonRes<DeviceDetailVO> res = hmpDeviceService.getDeviceDetail(userId, param);
        log.info("getDeviceDetail return:{}", res);
        return res;
    }

    @ApiOperation(value = "获取设备实时数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "设备SN码", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "second", value = "秒数，不传默认为0，不清楚这个参数的用途", paramType = "query", dataType = "int")
    })
    @GetMapping("/realTimeData")
    public CommonRes<DeviceRealTimeVO> getRealTimeData(@NotNull String sn, Integer second) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        Integer tenantId = RecoupUtil.getCurrentUser().getTenantId();
        log.info("getRealTimeData userId:{}, sn:{}, second{}", userId, sn, second);
        CommonRes<DeviceRealTimeVO> res = hmpDeviceService.getRealTimeData(userId, sn, second, tenantId);
        log.info("getRealTimeDataVo return:sn = {}, vo = {}", sn,JsonUtils.objectToJson(res.getData()));
        log.info("getRealTimeData return:sn = {}, breathBpm = {}", sn, res.getData().getBreathBpm());
        return res;
    }
    //-------------------test-start------------------//
    @GetMapping("/realTimeDataV7")
    public CommonRes<RealTimeDataVOV7> realTimeDataV7(@NotNull String sn, Integer second){
        Long userId = RecoupUtil.getCurrentUser().getId();
        Integer tenantId = RecoupUtil.getCurrentUser().getTenantId();
        CommonRes<RealTimeDataVOV7> realTimeDataV7 = hmpDeviceService.getMiniRealTimeDataV7(userId, sn, second, tenantId);
        return realTimeDataV7;
    }

    @GetMapping("/deleteV7RealTimeData")
    public CommonRes<Object> deleteV7RealTimeData(@NotNull String sn){
        log.info("deleteV7RealTimeData sn:{}",sn);
        hmpDeviceService.deleteV7RealTimeData(sn);
        return CommonRes.ok();
    }

    @Resource
    private RadarDataService radarDataService;
    @GetMapping("/test")
    public CommonRes<Object> test(){
        radarDataService.test();
        return CommonRes.ok();
    }


    //-------------------test-end------------------//
    @ApiOperation(value = "获取设备实时监测配置信息接口")
    @GetMapping("/realTimeMonitoring")
    @Deprecated
    @ApiIgnore
    public CommonRes<List<RealTimeMonitoring>> getRealTimeMonitoring() {
        log.info("getRealTimeMonitoring in");
        // TODO
        return CommonRes.ok();
    }

    @ApiOperation(value = "查询设备报警信息列表接口")
    @GetMapping("/alarmEventList")
    public CommonRes<IPage<AlarmEventItemVO>> getAlarmEventList(@Valid AlarmEventPageParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("getAlarmEventList userId:{}, param:{}", userId, param);
        CommonRes<IPage<AlarmEventItemVO>> res = hmpDeviceService.getAlarmEventList(userId, param);
        log.info("getAlarmEventList return:{}", res);
        return res;
    }

    @ApiOperation(value = "将报警信息设置为已读状态接口")
    @PostMapping("/readAlarmEvent")
    public CommonRes<Object> setReadAlarmEvent(@RequestBody @Valid AlarmEventFinishParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        Integer tenantId = RecoupUtil.getCurrentUser().getTenantId();
        log.info("setReadAlarmEvent userId:{}, tenantId:{}, param:{}", userId, tenantId, param);
        CommonRes<Object> res = hmpDeviceService.setReadAlarmEvent(userId, tenantId, param);
        log.info("setReadAlarmEvent return:{}", res);
        return res;
    }

    @ApiOperation(value = "获取单日睡眠报告基础数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "设备SN码", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "date", value = "日期，格式：2021-01-06", paramType = "query", dataType = "string", required = true)
    })
    @GetMapping("/sleepReportBasicOneDay")
    public CommonRes<HmpSleepReportBasicVO> getSleepReportBasicOneDay(@NotNull String sn, @NotNull String date) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("getSleepReportBasicOneDay userId:{}, sn:{}, date{}", userId, sn, date);
        HmpUserBindDevice hmpUserBindDevice = hmpUserBindDeviceService.getOne(Wrappers.<HmpUserBindDevice>lambdaQuery()
                .eq(HmpUserBindDevice::getUserId, userId).eq(HmpUserBindDevice::getDeviceSn, sn));
        if (hmpUserBindDevice == null) {
            return CommonRes.failed("用户未绑定该设备");
        }
        CommonRes<HmpSleepReportBasicVO> res = hmpHealthReportService.getSleepReportBasicOneDay(userId, sn, date,hmpUserBindDevice.getBedId());
        return res;
    }

    @ApiOperation(value = "获取单日睡眠报告图表数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "设备SN码", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "date", value = "日期，格式：2021-01-06", paramType = "query", dataType = "string", required = true)
    })
    @GetMapping("/sleepReportChartOneDay")
    public CommonRes<HmpSleepReportChartVO> getSleepReportChartOneDay(@NotNull String sn, @NotNull String date) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("getSleepReportBasicOneDay userId:{}, sn:{}, date{}", userId, sn, date);
        HmpUserBindDevice hmpUserBindDevice = hmpUserBindDeviceService.getOne(Wrappers.<HmpUserBindDevice>lambdaQuery()
        .eq(HmpUserBindDevice::getUserId, userId).eq(HmpUserBindDevice::getDeviceSn, sn));
        if (hmpUserBindDevice == null) {
            return CommonRes.failed("用户未绑定该设备");
        }
        CommonRes<HmpSleepReportChartVO> res = hmpHealthReportService.getSleepReportChartOneDay(userId, sn, date,hmpUserBindDevice.getBedId());
        return res;
    }

    @ApiOperation(value = "获取多日睡眠报告数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "设备SN码", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "startDate", value = "开始日期，格式：2021-01-06", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "endDate", value = "结束日期，格式：2021-01-06", paramType = "query", dataType = "string", required = true)
    })
    @GetMapping("/sleepReportMoreDay")
    public CommonRes<HmpSleepReportMoreVO> getSleepReportMoreDay(@NotNull String sn, @NotNull String startDate, @NotNull String endDate) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("getSleepReportMoreDay userId:{}, sn:{}, startDate{}, endDate{}", userId, sn, startDate, endDate);
        CommonRes<HmpSleepReportMoreVO> res = hmpHealthReportService.getSleepReportMoreDay(userId, sn, startDate, endDate);
        return res;
    }

    @ApiOperation(value = "进入实时数据模式接口")
    @PostMapping("/enterRealtime")
    public CommonRes<Object> enterRealtime(@RequestBody @Valid DeviceSnParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("enterRealtime userId:{}, param:{}", userId, param);
        CommonRes<Object> res = hmpDeviceService.enterRealtime(userId, param);
        log.info("enterRealtime return:{}", res);
        return res;
    }


    @ApiOperation(value = "查询设备更新状态")
    @PostMapping("/checkDeviceVersion")
    public CommonRes<CheckDeviceVersionVo> checkDeviceVersion(@RequestBody @Valid DeviceVersionParam param) {
        Long userId = RecoupUtil.getCurrentUser().getId();
        log.info("checkDeviceVersion userId:{}, param:{}", userId, param);
        param.setUserId(userId);
        CommonRes<CheckDeviceVersionVo> res = hmpDeviceService.checkDeviceVersion(param);
        log.info("checkDeviceVersion return:{}", res);
        return res;
    }



    @ApiOperation(value = "最新获取单日睡眠报告接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "设备SN码", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "date", value = "日期，格式：2021-01-06", paramType = "query", dataType = "string", required = true)
    })
    /**
     *
     * sourceType 1.web 2.小程序
     */
    @GetMapping("/getSleepReportOneDay")
    public CommonRes<HealthReportDayVo> getsleepReportOneDay(@NotNull String sn, @NotNull String date, Integer sourceType) {
        Long userId = null;
        if(null != sourceType && sourceType == 2){
           userId = RecoupUtil.getCurrentUser().getId();
        }
        log.info("getsleepReportOneDay userId:{}, sn:{}, date{}", userId, sn, date);
        CommonRes<HealthReportDayVo> res = hmpHealthReportService.getsleepReportOneDay(userId, sn, date,sourceType);
        return res;
    }

}
